#include "stdafx.h"
#include "NetworkModule.h"
#include <common.h>
#include <xml.h>
#include "session_manager.h"

using namespace utility::system;
using namespace utility::xml;

#ifdef WIN32
#pragma comment(lib, "net_module.lib")
#pragma comment(lib, "system.lib")
#pragma comment(lib, "strutil.lib")
#endif

CNetworkModule::CNetworkModule(void)
{
    m_pNetModule = get_net_module();
}


CNetworkModule::~CNetworkModule(void)
{
    destroy_net_module();
}

bool CNetworkModule::Init()
{
    string strConfigFile = utility::system::get_exe_path();
    strConfigFile += "/GSNetworkConfig.xml";
    if (!_LoadConfig(strConfigFile.c_str()))
    {
        LOG(CRITICAL) << "Failed on loading network configuration: " << strConfigFile;
        return false;
    }

    if (!m_strPort.empty())
    {
        try
        {
            m_pListener = m_pNetModule->create_listener();
            m_pListener->set_session_mgr(CPlayerSessionMgr::Instance());

            if (!m_pListener->start(m_strIP.c_str() ,m_strPort.c_str()))
            {
                LOG(CRITICAL) << "Failed to listen IP:" << m_strIP << " ,port:" << m_strPort;
                return false;
            }
        }
        catch(...)
        {
            return false;
        }
    }

    return true;
}

bool CNetworkModule::_LoadConfig( const char * szFileName )
{
    CMarkupSTL xmlDoc;
    if (!xmlDoc.Load(szFileName))
    {
        LOG(CRITICAL) << "Failed on open configuration file: " << szFileName << " Error:" << xmlDoc.GetError();
        return false;
    }

    if (!xmlDoc.FindElem("root"))
    {
        LOG(CRITICAL) << "Failed to find XML node: root";
        return false;
    }
    xmlDoc.IntoElem();

    if (!xmlDoc.FindElem("network"))
    {
        LOG(CRITICAL) <<  "Failed to find XML node: network";
        return false;
    }

    m_strLocalIPAddress = xmlDoc.GetAttrib("local_ip_address");
    if (m_strLocalIPAddress.empty())
    {
        LOG(CRITICAL) << "Failed to find XML attribution: network.local_ip_address";
        return false;
    }

    xmlDoc.IntoElem();

    while (xmlDoc.FindElem("client"))
    {
        string Port = xmlDoc.GetAttrib("listen_port");
        if (Port.length() == 0)
        {
            LOG(CRITICAL) << "Failed to find XML attribution: network.listen_port";
            return false;
        }

        string IP = xmlDoc.GetAttrib("ip_address");
        if (IP.length() == 0)
        {
            LOG(CRITICAL) << "Failed to find XML attribution: network.ip_address";
            return false;
        }

        string mode = xmlDoc.GetAttrib("mode");
        if (mode == "client")
        {
            m_strIP = IP;
            m_strPort = Port;
        }
    }

    return true;
}

bool CNetworkModule::Run()
{
    if (m_pNetModule)
        return m_pNetModule->run() > 0;
    return false;
}
